<?php
/**
 * Created by PhpStorm.
 * User: longli
 * Date: 2020/09/07
 * Time: 20:46
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\wms;


use app\admin\controller\BaseController;
use app\common\library\Tools;
use app\common\model\Account;
use app\common\model\Category;
use app\common\model\Producer;
use app\common\model\Product;
use app\common\model\ProductBrand;
use app\common\model\ProductSpec;
use app\common\model\ProductUnit;
use app\common\model\Warehouse;
use app\common\service\product\ProductService;
use app\common\status\BaseStatus;
use RuntimeException;

class ProductController extends BaseController
{
    /**
     * 商品列表
     * @return string|array
     * @date 2020/09/09
     * @author longli
     */
    public function index()
    {
        $this->assign('select_product', [
            'sku' => 'SKU',
            'platform_sku' => '平台SKU',
            'name_ch' => '商品中文名',
            'name_en' => '商品英文名',
            'producer_name' => '供应商',
            'unit_id' => '计量单位',
        ]);
        $this->assign('account', Account::getAll());
        $this->assign("product_status", Product::$STATUS);
        $this->assign('create_date', [-1 => '昨天', 0 => '今天', -6 => '7天前', -59 => '60天前']);
        $this->assign('sort', ['product_id' => '录入时间', 'name_ch' => '名称', 'brand' => '品牌', 'status' => '状态', 'model' => '型号']);
        $this->assign('status', Product::$STATUS);
        if($this->request->isAjax())
        {
            $products = ProductService::getInstance()->search($this->request->request());
            return apiResponsePage($products);
        }
        return $this->fetch("index");
    }

    /**
     * 录入商品
     * @return string
     * @date 2020/09/09
     * @author longli
     */
    public function edit()
    {
        $this->assign('brand', ProductBrand::getAll());
        $this->assign('unit', ProductUnit::getAll());
        $this->assign('status', Product::$STATUS);
        $this->assign('warehouse', Warehouse::getAll());
        $this->assign('producer', Producer::getAll());
        $this->assign('producer_defaults', Product::$IS_STATUS);
        $this->assign('producer_type', Producer::$LINE_TYPE);
        $this->assign('spec', Tools::sortArray(ProductSpec::getAll()->toArray(), 'type'));
        $productId = $this->request->get("product_id");
        if(!empty($productId) && $product = Product::with(['stores.stock', 'images', 'attrs', 'purchase'])->find($productId))
        {
            $this->assign("product", $product);
        }
        return $this->fetch('edit');
    }

    /**
     * 查看商品详情
     * @return mixed
     * @date 2020/09/14
     * @author longli
     */
    public function look()
    {
        $productId = $this->request->get("product_id");
        $product = Product::with(['stores.stock', 'images', 'sbrand', 'purchase', 'category'])->findOrFail($productId);
        $this->assign("product", $product);
        return $this->fetch('look');
    }

    /**
     * 更新商品状态
     * @return array
     * @date 2020/09/14
     * @author longli
     */
    public function update()
    {
        $productId = $this->request->post("product_id");
        if(empty($productId)) return apiResponse(BaseStatus::CODE_FAULT, [], '非法请求');
        $field = $this->request->post("field");
        $value = $this->request->post("value");
        if((is_array($field) && !is_array($value)) || (empty($field) || (empty($value) && !is_numeric($value))))  return apiResponse(BaseStatus::CODE_FAULT, [], '非法参数');
        if(is_array($field))
        {
            $data = [];
            foreach($field as $k => $f)
            {
                $data[$f] = $value[$k];
            }
        }
        else
        {
            $data = [$field => $value];
        }
        return Product::editByProductId($productId, $data)
            ? apiResponse(BaseStatus::CODE_NORMAL, [], '更新成功')
            : apiResponse(BaseStatus::CODE_FAULT, [], '更新失败');
    }

    /**
     * 保存商品
     * @return array
     * @date 2020/09/09
     * @author longli
     */
    public function save()
    {
        $json = $this->request->getContent();
        if(!Tools::isJson($json, $data)) return apiResponse(BaseStatus::CODE_FAULT, [], "非法请求");
        return ProductService::getInstance()->addProduct($data)
                 ? apiResponse(BaseStatus::CODE_NORMAL, [], "保存成功")
                 : apiResponse(BaseStatus::CODE_FAULT, [], "保存失败");
    }

    /**
     * 导出文件
     * @return array
     * @date 2020/09/13
     * @author longli
     */
    public function export()
    {
        $ids = $this->request->request("ids");
        $startDate = $this->request->request("start_date");
        $endDate = $this->request->request("end_date");
        if(empty($ids) && empty($startDate)) return apiResponse(BaseStatus::CODE_FAULT, [], "非法导出，请检查导出条件");
        $condition = [];
        if(!empty($ids)) $condition[] = ['product.product_id', 'in', $ids];
        if(!empty($startDate)) $condition = array_merge($condition, ProductService::getInstance()->parseLayuiRangeDate('product.create_time', $startDate));
        $productExport = new \app\common\service\export\Product();
        $file = $productExport->runExcel($condition);
        return apiResponse(BaseStatus::CODE_NORMAL, ["src" => urlencode($file)], "导出成功");
    }

    /**
     * 导入商品
     * @return array
     * @date 2020/09/13
     * @author longli
     */
    public function import()
    {
        $file = $this->request->request("path");
        if(Tools::startWith($file, '/')) $file = \Env::get("root_path") . "public{$file}";
        $productImport = new \app\common\service\import\Product($file);
        try
        {
            $productImport->run();
            return apiResponse(BaseStatus::CODE_NORMAL, [], '导入成功');
        }catch(RuntimeException $e)
        {
            return apiResponse(BaseStatus::CODE_FAULT, [], $e->getMessage());
        }
    }

    /**
     * 删除商品
     * @return array
     * @date 2020/09/02
     * @author longli
     */
    public function delete()
    {
        $ids = $this->request->get("ids");
        return ProductService::getInstance()->deleteProductById($ids)
            ? apiResponse(BaseStatus::CODE_NORMAL, [], '删除成功')
            : apiResponse(BaseStatus::CODE_FAULT, [], '删除失败');
    }

    /**
     * 获取自动生成 sku
     * @return array
     * @date 2020/09/09
     * @author longli
     */
    public function getskus()
    {
        $num = $this->request->get("num");
        $sku = $this->request->get("sku", '', 'trim');
        if(empty($num) || $num < 1) return apiResponse(BaseStatus::CODE_FAULT, [], '非法参数');
        $skus = empty($sku)
            ? ProductService::getInstance()->generateSameSku($num)
            : ProductService::getInstance()->addSameSku($sku, $num);
        return apiResponse(BaseStatus::CODE_NORMAL, !is_array($skus) ? [$skus]: $skus);
    }
}